//
//  SGQRCodeScanningVC.m
//  SGQRCodeExample
//
//  Created by kingsic on 17/3/20.
//  Copyright © 2017年 kingsic. All rights reserved.
//

#import "SGQRCodeScanningVC.h"
#import "SGQRCode.h"
#import "ScanSuccessJumpVC.h"
#import "WWebViewController.h"

@interface SGQRCodeScanningVC () <SGQRCodeScanManagerDelegate, SGQRCodeAlbumManagerDelegate>
@property (nonatomic, strong) SGQRCodeScanManager *manager;
@property (nonatomic, strong) SGQRCodeScanningView *scanningView;
@property (nonatomic, strong) UIButton *flashlightBtn;
@property (nonatomic, strong) UILabel *promptLabel;
@property (nonatomic, assign) BOOL isSelectedFlashlightBtn;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation SGQRCodeScanningVC

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.scanningView addTimer];
    [_manager resetSampleBufferDelegate];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.scanningView removeTimer];
    [self removeFlashlightBtn];
    [_manager cancelSampleBufferDelegate];
}

- (void)dealloc {
    WLog(@"SGQRCodeScanningVC - dealloc");
    [self removeScanningView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor clearColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.scanningView];
    [self setupNavigationBar];
    [self setupQRCodeScanning];
    [self.view addSubview:self.promptLabel];
    /// 为了 UI 效果
    [self.view addSubview:self.bottomView];
}

- (void)setupNavigationBar {
    self.navigationItem.title = @"扫码查验";
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"相册" style:(UIBarButtonItemStyleDone) target:self action:@selector(rightBarButtonItenAction)];
}

- (SGQRCodeScanningView *)scanningView {
    if (!_scanningView) {
        _scanningView = [[SGQRCodeScanningView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.9 * self.view.frame.size.height)];
//        _scanningView.scanningImageName = @"SGQRCode.bundle/QRCodeScanningLineGrid";
//        _scanningView.scanningAnimationStyle = ScanningAnimationStyleGrid;
//        _scanningView.cornerColor = [UIColor orangeColor];
    }
    return _scanningView;
}
- (void)removeScanningView {
    [self.scanningView removeTimer];
    [self.scanningView removeFromSuperview];
    self.scanningView = nil;
}

- (void)rightBarButtonItenAction {
    SGQRCodeAlbumManager *manager = [SGQRCodeAlbumManager sharedManager];
    [manager readQRCodeFromAlbumWithCurrentController:self];
    manager.delegate = self;

    if (manager.isPHAuthorization == YES) {
        [self.scanningView removeTimer];
    }
}

- (void)setupQRCodeScanning {
    self.manager = [SGQRCodeScanManager sharedManager];
    NSArray *arr = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    // AVCaptureSessionPreset1920x1080 推荐使用，对于小型的二维码读取率较高
//    if([_manager.session canSetSessionPreset:AVCaptureSessionPreset640x480] == YES)
//    {
//        [_manager setupSessionPreset:AVCaptureSessionPreset1920x1080 metadataObjectTypes:arr currentController:self];
//    } else {
        [_manager setupSessionPreset:AVCaptureSessionPreset1280x720 metadataObjectTypes:arr currentController:self];
//    }
//    [manager cancelSampleBufferDelegate];
    _manager.delegate = self;
}

#pragma mark - - - SGQRCodeAlbumManagerDelegate
- (void)QRCodeAlbumManagerDidCancelWithImagePickerController:(SGQRCodeAlbumManager *)albumManager {
    [self.view addSubview:self.scanningView];
}
- (void)QRCodeAlbumManager:(SGQRCodeAlbumManager *)albumManager didFinishPickingMediaWithResult:(NSString *)result {
    if ([result hasPrefix:@"http"]) {
        ScanSuccessJumpVC *jumpVC = [[ScanSuccessJumpVC alloc] init];
        jumpVC.jump_URL = result;
        [self.navigationController pushViewController:jumpVC animated:YES];
        
    } else {
        ScanSuccessJumpVC *jumpVC = [[ScanSuccessJumpVC alloc] init];
        jumpVC.jump_bar_code = result;
        [self.navigationController pushViewController:jumpVC animated:YES];
    }
}

#pragma mark - - - SGQRCodeScanManagerDelegate
- (void)QRCodeScanManager:(SGQRCodeScanManager *)scanManager didOutputMetadataObjects:(NSArray *)metadataObjects {
    WLog(@"metadataObjects - - %@", metadataObjects);
    if (metadataObjects != nil && metadataObjects.count > 0) {
        [scanManager palySoundName:@"SGQRCode.bundle/sound.caf"];
        [scanManager stopRunning];
        [scanManager videoPreviewLayerRemoveFromSuperlayer];

        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        NSString *zhQRcode = [obj stringValue];
        NSArray *arr = [zhQRcode componentsSeparatedByString:@","];
        if(arr.count==9||arr.count==8){
            NSString *fpdm = arr[2];
            NSString *fphm = arr[3];
            NSString *kjje = arr[4];
            NSString *kprq = arr[5];

            if(![self acq:kprq]){
                [self.navigationController popViewControllerAnimated:YES];
                [WShareUtil showAlert:@"温馨提示" message:@"开票日期已超过1年"];
            }else{
                //afcdm(fpdm);
                NSString *fplx = [self alxd:fpdm];
                if([fplx isEqualToString:@"04"]||[fplx isEqualToString:@"10"]||[fplx isEqualToString:@"11"]){
                    kjje = arr[6];
                    kjje = [kjje substringWithRange:NSMakeRange(kjje.length - 6, 6)];
                }
                WWebViewController *webVc = [[WWebViewController alloc] init];
                webVc.strTitle = @"发票明细";
                webVc.strUrl = [NSString stringWithFormat:@"http://fpcy.sx95113.com/iv/yzm.html?fpdm=%@&fphm=%@&kjje=%@&kprq=%@",fpdm,fphm,kjje,kprq];
                webVc.isQr = YES;
                [self.navigationController pushViewController:webVc animated:YES];
//        ScanSuccessJumpVC *jumpVC = [[ScanSuccessJumpVC alloc] init];
//        jumpVC.jump_URL = [obj stringValue];
//        [self.navigationController pushViewController:jumpVC animated:YES];
            }
        } else {
            WWebViewController *webVc = [[WWebViewController alloc] init];
            webVc.strUrl = zhQRcode;
            webVc.isQr = YES;
            [self.navigationController pushViewController:webVc animated:YES];
        }
    } else {
        [self.navigationController popViewControllerAnimated:YES];
        [WShareUtil showAlert:@"温馨提示" message:@"暂未识别出扫描的二维码"];
    }
}
- (void)QRCodeScanManager:(SGQRCodeScanManager *)scanManager brightnessValue:(CGFloat)brightnessValue {
    if (brightnessValue < - 1) {
        [self.view addSubview:self.flashlightBtn];
    } else {
        if (self.isSelectedFlashlightBtn == NO) {
            [self removeFlashlightBtn];
        }
    }
}

- (UILabel *)promptLabel {
    if (!_promptLabel) {
        _promptLabel = [[UILabel alloc] init];
        _promptLabel.backgroundColor = [UIColor clearColor];
        CGFloat promptLabelX = 0;
        CGFloat promptLabelY = 0.73 * self.view.frame.size.height;
        CGFloat promptLabelW = self.view.frame.size.width;
        CGFloat promptLabelH = 25;
        _promptLabel.frame = CGRectMake(promptLabelX, promptLabelY, promptLabelW, promptLabelH);
        _promptLabel.textAlignment = NSTextAlignmentCenter;
        _promptLabel.font = [UIFont boldSystemFontOfSize:13.0];
        _promptLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.6];
//        _promptLabel.text = @"将二维码/条码放入框内, 即可自动扫描";
        _promptLabel.text = @"请对准二维码进行扫描";
    }
    return _promptLabel;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.scanningView.frame), self.view.frame.size.width, self.view.frame.size.height - CGRectGetMaxY(self.scanningView.frame))];
        _bottomView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    }
    return _bottomView;
}

#pragma mark - - - 闪光灯按钮
- (UIButton *)flashlightBtn {
    if (!_flashlightBtn) {
        // 添加闪光灯按钮
        _flashlightBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        CGFloat flashlightBtnW = 30;
        CGFloat flashlightBtnH = 30;
        CGFloat flashlightBtnX = 0.5 * (self.view.frame.size.width - flashlightBtnW);
        CGFloat flashlightBtnY = 0.55 * self.view.frame.size.height;
        _flashlightBtn.frame = CGRectMake(flashlightBtnX, flashlightBtnY, flashlightBtnW, flashlightBtnH);
        [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"SGQRCodeFlashlightOpenImage"] forState:(UIControlStateNormal)];
        [_flashlightBtn setBackgroundImage:[UIImage imageNamed:@"SGQRCodeFlashlightCloseImage"] forState:(UIControlStateSelected)];
        [_flashlightBtn addTarget:self action:@selector(flashlightBtn_action:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _flashlightBtn;
}

- (void)flashlightBtn_action:(UIButton *)button {
    if (button.selected == NO) {
        [SGQRCodeHelperTool SG_openFlashlight];
        self.isSelectedFlashlightBtn = YES;
        button.selected = YES;
    } else {
        [self removeFlashlightBtn];
    }
}

- (void)removeFlashlightBtn {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SGQRCodeHelperTool SG_CloseFlashlight];
        self.isSelectedFlashlightBtn = NO;
        self.flashlightBtn.selected = NO;
        [self.flashlightBtn removeFromSuperview];
    });
}

-(NSString *)alxd:(NSString *)a{
    NSString *b;
    NSString *c = @"99";

    //特殊发票种类
    NSArray *code = [NSArray arrayWithObjects:@"144031539110",@"131001570151",@"133011501118",@"111001571071",nil];
    NSArray *code10 = [NSArray arrayWithObjects:@"1440315391",@"1310015701",@"1330115011",@"1110015710",nil];

    if(a.length==12){
        b = [a substringWithRange:NSMakeRange(7, 1)];
        for(int i=0; i<code.count; i++){
            if([a isEqualToString:code[i]]){
                c=@"10";
                break;
            }
        }
        if ([c isEqualToString:@"99"]) {  //增加判断，判断是否为新版电子票
            if ([a characterAtIndex:0] == '0' && [[a substringWithRange:NSMakeRange(10, 2)] isEqualToString:@"11"]) {
                c= @"10";
            }
            if (([a characterAtIndex:0] == '0') && ([[a substringWithRange:NSMakeRange(10, 2)] isEqualToString:@"06"] || [[a substringWithRange:NSMakeRange(10, 2)] isEqualToString:@"07"])) {  //判断是否为卷式发票  第1位为0且第11-12位为06或07
                c = @"11";
            }
        }
        if([c isEqualToString: @"99"]){ //如果还是99，且第8位是2，则是机动车发票
            if ([b isEqualToString:@"2"] && [a characterAtIndex:0] != '0') {
                c= @"03";
            }
        }

    }else if(a.length==10){
        b=[a substringWithRange:NSMakeRange(7, 2)];
        if([b isEqualToString:@"1"]||[b isEqualToString:@"5"]){
            c = @"01";
        }else if([b isEqualToString:@"6"]||[b isEqualToString:@"3"]){
            c = @"04";
        }else if([b isEqualToString:@"7"]||[b isEqualToString:@"2"]){
            c = @"02";
        }
    }
    return c;
}

- (NSString *)acq:(NSString *)a {
    NSString *b = @"^\\d{8}$";
    NSString *c = @"^0{8}$";
    NSString *d= @"^0{11}-?[1-9]*\\w\\d*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", b];
    if([pred evaluateWithObject:a]){
        NSDateComponents *g = [self getCurrentNSDateComponents];
        NSInteger h = g.year;
        NSInteger i = g.month;
        NSInteger j = [[self getCurrentTime] integerValue];
        NSInteger k = [[a substringWithRange:NSMakeRange(0, 4)] integerValue];
        NSInteger l =  [[a substringWithRange:NSMakeRange(4, 2)] integerValue];
        NSInteger m =  [[a substringWithRange:NSMakeRange(6, 1)] integerValue];
        NSInteger n = [self ca:0];
        NSInteger t = [self ca:1];
        if((h!=k&&h-1!=k)||l == 0 || l>12|| m == 0 || m>31 || a.integerValue>n||![self cb:k b:l c:m] ||(h==k && i== l && j==m)){
            return false;
        }
        if(h-1==k&&a.integerValue<=t){
            return false;
        }
        return @"true";
    }else{
        return @"false";
    }
}

- (NSInteger)cb:(NSInteger)a b:(NSInteger)b c:(NSInteger)c{
    if(c>31){
        return false;
    }else if(c<1){
        return false;
    }else{
        if(b==2){
            if(c>29){//2月不会超过29
                return false;
            }

            if ((((a%4)==0) && ((a%100)!=0)) || ((a%400)==0)) {//闰年1--29
                return true;
            }else{//平年1--28
                if(c>28){
                    return false;
                }
            }
        }else if((b==4||b==6||b==9||b==11)&&c>30){
            return false;
        }
    }
    return true;
}

- (NSInteger)ca:(int)i {
    NSDateComponents *a = [self getCurrentNSDateComponents];
    NSInteger b = 0;
    NSInteger c = 0;
    NSInteger d = 0;
    NSString *e = @"";
    b = a.year - i;
    c = a.month;
    d = a.day;
    e = [NSString stringWithFormat:@"%@%ld",e,b];
    if (c >= 10 ){
        e = [NSString stringWithFormat:@"%@%ld",e,c];
    }else{
        e = [NSString stringWithFormat:@"%@0%ld",e,c];
    }
    if (d >= 10 ){
        e = [NSString stringWithFormat:@"%@%ld",e,d];
    }else{
        e = [NSString stringWithFormat:@"%@0%ld",e,d];
    }
    return e.integerValue;

}

//获取当地时间
- (NSDateComponents *)getCurrentNSDateComponents {
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags
                                          fromDate:dt];
    // 获取各时间字段的数值
    WLog(@"现在是%ld年" , comp.year);
    WLog(@"现在是%ld月 " , comp.month);
    WLog(@"现在是%ld日" , comp.day);
    WLog(@"现在是%ld时" , comp.hour);
    WLog(@"现在是%ld分" , comp.minute);
    WLog(@"现在是%ld秒" , comp.second);
    WLog(@"现在是星期%ld" , comp.weekday);

    return comp;
}

//获取当地时间
- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

@end

